package no.kolstad.movies.dao.hibernate;
/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import java.util.Set;
import no.kolstad.movies.model.Movie;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;

import no.kolstad.movies.dao.UserDAO;
import no.kolstad.movies.model.User;

public class UserDAOHibernate extends BaseDAOHibernate<User> implements UserDAO {
  @Override
  protected Class<User> getModelClass() {
    return User.class;
  }

  @Override
  public UserDetails loadUserByUsername(String username) {
    User user = get(username);
    if (user == null) {
      throw new UsernameNotFoundException("User not found");
    }

    if (user.getRoles().size() == 0) {
      throw new UsernameNotFoundException("User has no roles");
    }

    return user;
  }

  public User get(String username) {
    List<User> users = findByNamedQueryAndNamedParam("user.byName", "name",
        username);
    if (!users.isEmpty()) {
      return users.get(0);
    }
    if (logger.isErrorEnabled()) {
      logger.error("Couldn't find user with username: " + username);
    }
    return null;
  }

  @Override
  public Set<Movie> getMovieCollection(User user) {
    List<Movie> movies = getHibernateTemplate().findByNamedQueryAndNamedParam("movies.for.user", "user", user);
    Set<Movie> myMovies = new HashSet<Movie>();
    Iterator<Movie> movIterator = movies.iterator();
    while(movIterator.hasNext()) {
      Movie m = movIterator.next();
      myMovies.add(m);
    }
    return myMovies;
  }

  @Override
  public Set<Movie> getMovieCollection(Long user_id) {
    return getMovieCollection(get(user_id));
  }

  
}

